package com.pomr.service.simstorage.impl;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pomr.dao.simstorage.SimInStorageDao;
import com.pomr.model.menu.EquipmentCondition;
import com.pomr.model.menu.EquipmentStatus;
import com.pomr.model.simstorage.SimInStorage;
import com.pomr.model.simstorage.SimStorage;
import com.pomr.model.simstorage.SimStorageDetail;
import com.pomr.service.simstorage.SimInStorageService;
import com.pomr.util.page.Page;
@Service
public class SimInStorageServiceImpl implements SimInStorageService{
	@Autowired
	@Qualifier("simInStorageDaoImpl")
	private SimInStorageDao simInStorageDao;

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean inStorage(SimInStorage storage) throws Exception {
		//入库记录
		return simInStorageDao.add(storage);
		//库存主表（更新库存等）
//		SimStorage estorage = new SimStorage();
//		estorage.setAgency(storage.getAgency());
//		System.out.println(storage.getAppid());
//		estorage.setNetworkOperator(storage.getNetworkOperator());
//		estorage.setManufacturer(storage.getManufacturer());
//		String hql = "from SimStorage where networkOperator.id="+estorage.getNetworkOperator().getId()+" and manufacturer.id="
//				+estorage.getManufacturer().getId()+" and agency.id="+estorage.getAgency().getId();
//		List<SimStorage> es = simInStorageDao.findByHql(hql);
//		Integer estorageid = null;
//		if(es==null || es.size()<=0){//不存在库存 --保存
//			estorage.setStockNumber(storage.getNumber());
//			if((estorageid = simInStorageDao.addNumKey(estorage))==null){
//				throw new Exception("保存库存记录失败");
//			}
//		}else{//已存在库存--更新库存数据
//			SimStorage estor = es.get(0);
//			estor.setStockNumber(estor.getStockNumber()+storage.getNumber());
//			if(!simInStorageDao.editEntity(estor)){
//				throw new Exception("更新库存记录失败");
//			}
//			estorageid = estor.getId();
//		}
//		//库存明细表
//		String endsn = storage.getEndSN();
//		String startsn = storage.getStartSN();
//		String imsiendsn = storage.getEndIMSI();
//		String imsistartsn = storage.getStartIMSI();
//		boolean isLX = true;
//		if(imsiendsn==null || "".equals(imsiendsn)){//非连续IMSI
//			isLX = false;
//		}
//		if(endsn==null || "".equals(endsn)){//非连续SN码
//			String[] sns = startsn.split(";");
//			System.out.println(estorageid);
//			for(int i=0; i<sns.length; i++){
//				SimStorage stor = new SimStorage();
//				stor.setId(estorageid);
//				System.out.println("--------"+sns[i]);
//				EquipmentStatus status = new EquipmentStatus();
//				EquipmentCondition con = new EquipmentCondition();
//				status.setId(1);//空闲状态
//				SimStorageDetail detail = new SimStorageDetail();//新建对象 不然会报错
//				detail.setAgency(storage.getAgency());
//				detail.setNetworkOperator(storage.getNetworkOperator());
//				detail.setManufacturer(storage.getManufacturer());
//				detail.setSimStorage(stor);
//				detail.setId(null);
//				detail.setEquipmentStatus(status);
//				detail.setAppid(storage.getAppid());
//				
//				if(imsistartsn!=null && !"".equals(imsistartsn.trim())){//存在imei
//					int ilen = imsistartsn.length();//编码长度
//					if(isLX){//连续
//						long stratimei =  Long.parseLong(imsistartsn.trim());
//						String imei = "00000000000000000000000000"+(stratimei+i);
//						imei = imei.substring(imei.length()-ilen);
//						detail.setImsi(storage.getPrefixIMSI()+imei+storage.getSubfixIMSI());
//					}else{//非连续
//						String[] imeis = imsistartsn.split(",");
//						System.out.println(imeis[i]);
//						if(imeis.length<=(i+1)){
//							detail.setImsi(storage.getPrefixIMSI()+imeis[i]+storage.getSubfixIMSI());
//						}
//					}
//				}
//				
//				con.setId(1);
//				detail.setEquipmentCon(con);
//				detail.setsN(storage.getPrefix()+sns[i]+storage.getSubfix());
//				if(!simInStorageDao.add(detail)){
//					throw new Exception("更新库存记录明细失败");
//				}
//			}
//		}else{//连续SN码
//			long strat =  Long.parseLong(startsn);
//			long end =  Long.parseLong(endsn);
//			int len = startsn.length();//编码长度
//			int j = 0;
//			for(long i=strat;i<=end;i++){
//				SimStorage stor = new SimStorage();
//				stor.setId(estorageid);
//				System.out.println("--------"+i);
//				EquipmentStatus status = new EquipmentStatus();
//				EquipmentCondition con = new EquipmentCondition();
//				status.setId(1);//空闲状态
//				SimStorageDetail detail = new SimStorageDetail();//新建对象 不然会报错
//				detail.setAgency(storage.getAgency());
//				detail.setNetworkOperator(storage.getNetworkOperator());
//				detail.setManufacturer(storage.getManufacturer());
//				detail.setSimStorage(stor);
//				detail.setId(null);
//				detail.setEquipmentStatus(status);
//				detail.setAppid(storage.getAppid());
//				if(imsistartsn!=null && !"".equals(imsistartsn.trim())){//存在imsi
//					int ilen = imsistartsn.length();//编码长度
//					if(isLX){//连续
//						long stratimei =  Long.parseLong(imsistartsn.trim());
//						String imei = "00000000000000000000000000"+(stratimei+j);
//						imei = imei.substring(imei.length()-ilen);
//						detail.setImsi(storage.getPrefixIMSI()+imei+storage.getSubfixIMSI());
//					}else{//非连续
//						String[] imeis = imsistartsn.split(",");
//						if(imeis.length<=(i+1)){
//							detail.setImsi(storage.getPrefixIMSI()+imeis[j]+storage.getSubfixIMSI());
//						}
//					}
//				}
//				
//				con.setId(1);
//				detail.setEquipmentCon(con);
//				//编码补足0
//				String sns = "00000000000000000000000000"+i;
//				sns = sns.substring(sns.length()-len);
//				detail.setsN(storage.getPrefix()+sns+storage.getSubfix());
//				System.out.println(i);
//				j++;
//				if(!simInStorageDao.add(detail)){
//					throw new Exception("更新库存记录明细失败");
//				}
//			}
//			
//			
//		}
//		//查询库存数是否准确
//		es = simInStorageDao.findByHql(hql);
//		if(es.get(0).getStockNumber()<0){
//			throw new Exception("库存数不能为负");
//		}
	}

	@Override
	public Page<List<SimInStorage>> searchSimInStorages(String networkid, String agencyid, String manufacturerid,
			String time1, String time2, String page, String limit) throws Exception {
		StringBuilder sb = new StringBuilder();
		sb.append("from SimInStorage ");
		int i=0;
		if(networkid!=null && !networkid.equals("")){
			i++;
			sb.append("where networkOperator.id = "+networkid+" ");
		}
		if(agencyid!=null && !agencyid.equals("")){
			
			if(i>0){
				sb.append("and ");
			}else{
				sb.append("where ");
			}
			sb.append("agency.id = "+agencyid+" ");
			i++;
		}
		if(manufacturerid!=null && !manufacturerid.equals("")){
			
			if(i>0){
				sb.append("and ");
			}else{
				sb.append("where ");
			}
			sb.append("manufacturer.id = "+manufacturerid+" ");
			i++;
		}
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		Map<String, Object> parammap = new HashMap<String, Object>();
		boolean istime = false;
		if(time1!=null && !time1.equals("")){
			if(i>0){
				sb.append("and ");
			}else{
				sb.append("where ");
			}
			sb.append("inTime >= :startDate ");
			parammap.put("startDate", sf.parse(time1));
			i++;
			istime = true;
		}
		if(time2!=null && !time2.equals("")){
			if(i>0){
				sb.append("and ");
			}else{
				sb.append("where ");
			}
			sb.append("inTime <= :endDate ");
			parammap.put("endDate", sf.parse(time2));
			i++;
			istime = true;
		}
		sb.append(" order by inTime desc ");
		String hqlStr = sb.toString();
		Page<List<SimInStorage>> p = new Page<List<SimInStorage>>();
		p.setCunrrentPage(Integer.valueOf(page));
		p.setPageSize(Integer.valueOf(limit));
		if(!istime){
			return simInStorageDao.showPage(hqlStr, "select count(1) "+hqlStr, p);
		}
		return simInStorageDao.showPageParam(hqlStr, "select count(1) "+hqlStr, p,parammap);
	}

	@Override
	public SimInStorage searchSimInStorageById(SimInStorage instor) throws Exception {
		String hql = "from SimInStorage e left join fetch e.networkOperator left join fetch e.manufacturer "
				+ "left join fetch e.agency left join fetch e.inUser left join fetch e.createUser where e.id="+instor.getId();
		List<SimInStorage> es = simInStorageDao.findByHql(hql);
		if(es==null || es.size()<=0){
			return null;
		}
		return es.get(0);
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean deleteSimInStorageById(String[] ids, String del) throws Exception {
		SimInStorage instor = null;
		for(String id:ids){
			// TODO 仅可删除未经审核过的入库记录
			instor = simInStorageDao.getById(SimInStorage.class, Integer.valueOf(id));
			if(instor.getState()!=null && instor.getState().equals("1")){//已审核
				throw new Exception("入库记录已审核无法删除，id："+id);
			}
			if(simInStorageDao.removeEntity(instor)){//删除成功
				
			}else{
				throw new Exception("入库记录删除失败");
			}
		}
		
		return true;
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean reviewSimInStorageById(String[] ids) throws Exception {
		SimInStorage instor = null;
		for(String id:ids){
			instor = simInStorageDao.getById(SimInStorage.class, Integer.valueOf(id));
			instor.setState("1");
			if(simInStorageDao.editEntity(instor)){//审核成功
				//TODO 更新库存记录
				//库存主表（更新库存等）
				SimStorage estorage = new SimStorage();
				estorage.setAgency(instor.getAgency());
				estorage.setNetworkOperator(instor.getNetworkOperator());
				estorage.setManufacturer(instor.getManufacturer());
				String hql = "from SimStorage where networkOperator.id="+estorage.getNetworkOperator().getId()+" and manufacturer.id="
						+estorage.getManufacturer().getId()+" and agency.id="+estorage.getAgency().getId();
				List<SimStorage> es = simInStorageDao.findByHql(hql);
				Integer estorageid = null;
				if(es==null || es.size()<=0){//不存在库存 --保存
					estorage.setStockNumber(instor.getNumber());
					if((estorageid = simInStorageDao.addNumKey(estorage))==null){
						throw new Exception("保存库存记录失败");
					}
				}else{//已存在库存--更新库存数据
					SimStorage estor = es.get(0);
					estor.setStockNumber(estor.getStockNumber()+instor.getNumber());
					if(!simInStorageDao.editEntity(estor)){
						throw new Exception("更新库存记录失败");
					}
					estorageid = estor.getId();
				}
				//库存明细表
				String endsn = instor.getEndSN();
				String startsn = instor.getStartSN();
				String imsiendsn = instor.getEndIMSI();
				String imsistartsn = instor.getStartIMSI();
				boolean isLX = true;
				if(imsiendsn==null || "".equals(imsiendsn)){//非连续IMSI
					isLX = false;
				}
				String starticcid = instor.getStarticcid();
				String endiccid = instor.getEndiccid();
				boolean isLXICC = true;
				if(endiccid==null || "".equals(endiccid)){//非连续ICCID
					isLXICC = false;
				}
				if(endsn==null || "".equals(endsn)){//非连续SN码
					String[] sns = startsn.split(";");
					System.out.println(estorageid);
					for(int i=0; i<sns.length; i++){
						SimStorage stor = new SimStorage();
						stor.setId(estorageid);
						System.out.println("--------"+sns[i]);
						EquipmentStatus status = new EquipmentStatus();
						EquipmentCondition con = new EquipmentCondition();
						status.setId(1);//空闲状态
						SimStorageDetail detail = new SimStorageDetail();//新建对象 不然会报错
						detail.setSimStorage(stor);
						detail.setId(null);
						detail.setEquipmentStatus(status);
						detail.setAppid(instor.getAppid());
						
						if(imsistartsn!=null && !"".equals(imsistartsn.trim())){//存在imei
							int ilen = imsistartsn.length();//编码长度
							if(isLX){//连续
								long stratimei =  Long.parseLong(imsistartsn.trim());
								String imei = "00000000000000000000000000"+(stratimei+i);
								imei = imei.substring(imei.length()-ilen);
								detail.setImsi(instor.getPrefixIMSI()+imei+instor.getSubfixIMSI());
							}else{//非连续
								String[] imeis = imsistartsn.split(",");
								System.out.println(imeis[i]);
								if(imeis.length<=(i+1)){
									detail.setImsi(instor.getPrefixIMSI()+imeis[i]+instor.getSubfixIMSI());
								}
							}
						}
						
						if(starticcid!=null && !"".equals(starticcid.trim())){//存在iccid
							int ilen = starticcid.length();//编码长度
							if(isLXICC){//连续
								long stratimei =  Long.parseLong(starticcid.trim());
								String iccid = "00000000000000000000000000"+(stratimei+i);
								iccid = iccid.substring(iccid.length()-ilen);
								detail.setIccid(instor.getPreiccid()+iccid+instor.getSubficcid());
							}else{//非连续
								String[] iccids = starticcid.split(",");
								System.out.println(iccids[i]);
								if(iccids.length<=(i+1)){
									detail.setIccid(instor.getPreiccid()+iccids[i]+instor.getSubficcid());
								}
							}
						}
						
						con.setId(1);
						detail.setEquipmentCon(con);
						detail.setsN(instor.getPrefix()+sns[i]+instor.getSubfix());
						if(!simInStorageDao.add(detail)){
							throw new Exception("更新库存记录明细失败");
						}
					}
				}else{//连续SN码
					long strat =  Long.parseLong(startsn);
					long end =  Long.parseLong(endsn);
					int len = startsn.length();//编码长度
					int j = 0;
					for(long i=strat;i<=end;i++){
						SimStorage stor = new SimStorage();
						stor.setId(estorageid);
						System.out.println("--------"+i);
						EquipmentStatus status = new EquipmentStatus();
						EquipmentCondition con = new EquipmentCondition();
						status.setId(1);//空闲状态
						SimStorageDetail detail = new SimStorageDetail();//新建对象 不然会报错
						detail.setSimStorage(stor);
						detail.setId(null);
						detail.setEquipmentStatus(status);
						detail.setAppid(instor.getAppid());
						if(imsistartsn!=null && !"".equals(imsistartsn.trim())){//存在imsi
							int ilen = imsistartsn.length();//编码长度
							if(isLX){//连续
								long stratimei =  Long.parseLong(imsistartsn.trim());
								String imei = "00000000000000000000000000"+(stratimei+j);
								imei = imei.substring(imei.length()-ilen);
								detail.setImsi(instor.getPrefixIMSI()+imei+instor.getSubfixIMSI());
							}else{//非连续
								String[] imeis = imsistartsn.split(",");
								if(imeis.length<=(i+1)){
									detail.setImsi(instor.getPrefixIMSI()+imeis[j]+instor.getSubfixIMSI());
								}
							}
						}
						
						if(starticcid!=null && !"".equals(starticcid.trim())){//存在iccid
							int ilen = starticcid.length();//编码长度
							if(isLXICC){//连续
								long straticcid =  Long.parseLong(starticcid.trim());
								String iccid = "00000000000000000000000000"+(straticcid+j);
								iccid = iccid.substring(iccid.length()-ilen);
								detail.setIccid(instor.getPreiccid()+iccid+instor.getSubficcid());
							}else{//非连续
								String[] iccids = starticcid.split(",");
								if(iccids.length<=(i+1)){
									detail.setIccid(instor.getPreiccid()+iccids[j]+instor.getSubficcid());
								}
							}
						}
						
						con.setId(1);
						detail.setEquipmentCon(con);
						//编码补足0
						String sns = "00000000000000000000000000"+i;
						sns = sns.substring(sns.length()-len);
						detail.setsN(instor.getPrefix()+sns+instor.getSubfix());
						System.out.println(i);
						j++;
						if(!simInStorageDao.add(detail)){
							throw new Exception("更新库存记录明细失败");
						}
					}
					
					
				}
				//查询库存数是否准确
				es = simInStorageDao.findByHql(hql);
				if(es.get(0).getStockNumber()<0){
					throw new Exception("库存数不能为负");
				}
			}else{
				throw new Exception("入库记录审核失败");
			}
		}
		
		return true;
	}
}
